package com.tv.enoguia.Utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

public class CustomViewPager extends ViewPager {

	private boolean enabled;
	float mStartDragX;
	OnSwipeOutListener mListener;

	public CustomViewPager(Context context) {
		super(context);
		this.enabled = true;
	}

	public CustomViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.enabled = true;
	}
	
	Handler mHandler = new Handler();

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		float x = ev.getX();
		if (this.enabled) {
			if(ev.getAction()==MotionEvent.ACTION_UP) {
				if(mStartDragX>=0) {
					if (mStartDragX+80 < x && getCurrentItem() == 0) {
						if(mListener!=null)
							mListener.onSwipeOutAtStart();
					} else if (mStartDragX-80 > x
							&& getCurrentItem() == getAdapter().getCount() - 1) {
						if(mListener!=null)
							mListener.onSwipeOutAtEnd();
					}
					mStartDragX = -1;
				}
			}
			return super.onTouchEvent(ev);
		}
		return false;
	}

	public void setPagingEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public void setOnSwipeOutListener(OnSwipeOutListener listener) {
		mListener = listener;
	}
	
	Runnable resetX = new Runnable() {
		
		@Override
		public void run() {
			mStartDragX = -1;
		}
	};

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		if (this.enabled) {
			Log.e("Tuan", "Tuan "+ev.getAction());
			float x = ev.getX();
			switch (ev.getAction()) {
			case MotionEvent.ACTION_DOWN:
				mStartDragX = x;
				mHandler.removeCallbacks(resetX);
				mHandler.postDelayed(resetX, 300);
				break;
			}
			return super.onInterceptTouchEvent(ev);
		}
		return false;
	}

	public interface OnSwipeOutListener {
		public void onSwipeOutAtStart();

		public void onSwipeOutAtEnd();
	}
}
